package com.swgk.core.base.di;

import com.swgk.core.base.api.BaseApiSource;
import com.swgk.core.base.api.BaseApiSourceImpl;
import com.swgk.core.base.model.factory.CommonInterceptor;
import com.swgk.core.base.model.factory.CryptoConverterFactory;
import com.swgk.core.base.model.preference.BasePreferenceSource;
import com.swgk.core.util.MLog;

import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Description:
 * Author zhengkewen
 * Time 2017/12/11
 */
@Module
public class NetworkModule {
    private static final String BASE_URL = "";
    private static final String TAG = "api";
    private BaseApiSourceImpl baseApiSource;
    private String baseUrl;

    public NetworkModule(BaseApiSourceImpl baseApiSource, String baseUrl) {
        this.baseApiSource = baseApiSource;
        this.baseUrl = baseUrl;
    }

    @Provides
    @Singleton
    OkHttpClient provideOkHttpClient(final BasePreferenceSource preferenceSource) {
        final OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
        okHttpClient.connectTimeout(8000, TimeUnit.SECONDS);
        //添加接口拦截器
        okHttpClient.addInterceptor(new CommonInterceptor(preferenceSource));
        return okHttpClient.build();
    }

    @Provides
    @Singleton
    Retrofit provideRetrofit(OkHttpClient okHttpClient) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(CryptoConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();
        return retrofit;
    }

    @Provides
    @Singleton
    BaseApiSource provideBaseApiSource(final Retrofit retrofit) {
        baseApiSource.setRetrofit(retrofit);
        return baseApiSource;
    }
}
